#include "Texture.h"
// include DevIL for image loading
#include <IL/il.h>

Texture::Texture(GLenum textureTarget, const std::string& fileName)
{
	mTextureTarget = textureTarget;
	mFileName = fileName;
}
Texture::~Texture(void)
{
	// Delete texture object
	glDeleteTextures ( 1, &mTextureObj );
}
bool Texture::Load()
{
	ILboolean success;

	/* initialization of DevIL */
	ilInit(); 
	ILuint imageID = ilGenImage(); 
	ilBindImage(imageID); /* Binding of DevIL image name */
	ilEnable(IL_ORIGIN_SET);
	ilOriginFunc(IL_ORIGIN_LOWER_LEFT); 
	success = ilLoadImage((ILstring)mFileName.c_str());
	GLuint texId;
	glGenTextures ( 1, &mTextureObj );

	if (success) {
		/* Convert image to RGBA */
		ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE); 

		/* Create and load textures to OpenGL */
		glBindTexture(GL_TEXTURE_2D, mTextureObj); 
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
		glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, ilGetInteger(IL_IMAGE_WIDTH),
			ilGetInteger(IL_IMAGE_HEIGHT), 0, GL_RGBA, GL_UNSIGNED_BYTE,
			ilGetData()); 
	}
	else 
		printf("Couldn't load Image: %s\n", mFileName);
	/* Because we have already copied image data into texture data
	we can release memory used by image. */
	ilDeleteImage(1); 
	return success;
}
void Texture::Bind(GLenum textureUnit)
{
	glActiveTexture(textureUnit);
	glBindTexture(mTextureTarget, mTextureObj);
}
